#pragma once
#include <iostream>
#include <time.h>
#include <string>
#include <stdarg.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;
#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4
#define SIZE 1024
#define Scream 0
#define OneFile 1
#define ClassFile 2
#define LogFile "log.txt"
#define Path "./log/"

class Log
{
public:
	string levelToString(int level)
	{
		switch (level)
		{
		case Info:
			return "Info";
			break;
		case Debug:
			return "Debug";
			break;
		case Warning:
			return "Warning";
			break;
		case Error:
			return "Error";
			break;
		case Fatal:
			return "Fatal";
			break;
		default:
			return "None";
			break;
		}
	}

	Log()
	{
		printMethod = Scream;
		pathName = Path;
	}

	~Log()
	{}

	void Enable(int method)
	{
		printMethod = method;
	}
	
	void printOneFile(const string& logName, const string& logtxt)
	{
		string _logName = pathName + logName;
		int fd = open(_logName.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
		if (fd < 0) return;
		write(fd, logtxt.c_str(), logtxt.size());
		close(fd);
	}

	void printClassFile(int level, const string& logtxt)
	{
		string fileName = LogFile;
		fileName += ".";
		fileName += levelToString(level);

		printOneFile(fileName, logtxt);
	}

	void printLog(int level, const string& logtxt)
	{
		switch (printMethod)
		{
			case Scream:
				cout << logtxt << endl;
				break;
			case OneFile:
				printOneFile(LogFile, logtxt);
				break;
			case ClassFile:
				printClassFile(level, logtxt);
				break;
			default:
				break;
		}
	}

	void operator()(int level, const char *format, ...)
	{
		time_t t = time(nullptr);
		struct tm *ctime = localtime(&t);

		char buffer1[SIZE];
		snprintf(buffer1, sizeof(buffer1), "[%s][%d-%d-%d %d-%d-%d]", levelToString(level).c_str(), \
				 ctime->tm_year + 1900, ctime->tm_mon + 1, ctime->tm_mday, \
				 ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

		va_list s;
		va_start(s, format);
		char buffer2[SIZE];
		vsnprintf(buffer2, sizeof(buffer2), format, s);
		va_end(s);

		char logtxt[SIZE * 2];
		snprintf(logtxt, sizeof(logtxt), "%s %s\n", buffer1, buffer2);

		// printf("%s\n", logtxt);
		printLog(level, logtxt);
	}

private:
	int printMethod;
	string pathName;
};
